﻿(function ($) {

    // *********************************************
    //  EasyWeb Namespace
    // *********************************************

    window.EasyWeb = function () {
    }

    // *********************************************
    //  Layout
    // *********************************************

    EasyWeb.EWMaster = (function () {
        return {
            init: function () {
            }
        };
    })();

    // *********************************************
    //  Helpers
    // *********************************************

    EasyWeb.EWHelpers = function () {
    }

    EasyWeb.EWHelpers.getFunction = function (code, argNames) {
        var fn = window, parts = (code || "").split(".");
        while (fn && parts.length) {
            fn = fn[parts.shift()];
        }
        if (typeof (fn) === "function") {
            return fn;
        }
        argNames.push(code);
        return Function.constructor.apply(null, argNames);
    }

    EasyWeb.EWHelpers.confirmDialog = function (text, action, windowTitle, okButtonText, cancelButtonText, closeText) {
        $("<div></div>").text(text).dialog({
            closeText: closeText,
            modal: true,
            title: windowTitle,
            close: function () {
                $(this).dialog("destroy");
            },
            buttons: [{
                text: okButtonText,
                click: function () {
                    var result = action();
                    if (result !== false) {
                        $(this).dialog("close");
                    }
                }
            }, {
                text: cancelButtonText,
                click: function () {
                    $(this).dialog("close");
                }
            }]
        });
    }

    EasyWeb.EWHelpers.confirmDialogAsync = function (text, action, success, error, windowTitle, okButtonText, cancelButtonText, closeText) {
        $("<div></div>").text(text).dialog({
            closeText: closeText,
            modal: true,
            title: windowTitle,
            close: function () {
                $(this).dialog("destroy");
            },
            buttons: [{
                text: okButtonText,
                click: function () {
                    var dlg = $(this);
                    $.when($.isFunction(action) ? action() : action)
                     .done(function () {
                         var result = success(arguments);
                         if (result !== false) {
                             dlg.dialog("close");
                         }
                     })
                     .fail(function () {
                         error(arguments);
                     });
                }
            }, {
                text: cancelButtonText,
                click: function () {
                    $(this).dialog("close");
                }
            }]
        });
    }

    EasyWeb.EWHelpers.messageDialog = function (text, windowTitle, buttonText, closeText) {
        $("<div></div>").text(text).dialog({
            closeText: closeText,
            modal: true,
            title: windowTitle,
            close: function () {
                $(this).dialog("destroy");
            },
            buttons: [{
                text: buttonText,
                click: function () {
                    $(this).dialog("close");
                }
            }]
        });
    }

    EasyWeb.EWHelpers.modalDialog = function (windowTitle, html, action, okButtonText, cancelButtonText, closeText, width, height) {
        $("<div></div>").html(html).dialog({
            closeText: closeText,
            modal: true,
            title: windowTitle,
            width: width ? width : 300,
            height: height ? height : "auto",
            close: function () {
                $(this).dialog("destroy");
            },
            buttons: [{
                text: okButtonText,
                click: function () {
                    var result = action();
                    if (result !== false) {
                        $(this).dialog("close");
                    }
                }
            }, {
                text: cancelButtonText,
                click: function () {
                    $(this).dialog("close");
                }
            }]
        });
    }

    EasyWeb.EWHelpers.modalDialogAsync = function (windowTitle, html, action, success, error, okButtonText, cancelButtonText, closeText, width, height) {
        $("<div></div>").html(html).dialog({
            closeText: closeText,
            modal: true,
            title: windowTitle,
            width: width ? width : 300,
            height: height ? height : "auto",
            close: function () {
                $(this).dialog("destroy");
            },
            buttons: [{
                text: okButtonText,
                click: function () {
                    var dlg = $(this);
                    $.when($.isFunction(action) ? action() : action)
                     .done(function () {
                         var result = success(arguments);
                         if (result !== false) {
                             dlg.dialog("close");
                         }
                     })
                     .fail(function () {
                         error(arguments);
                     });
                }
            }, {
                text: cancelButtonText,
                click: function () {
                    $(this).dialog("close");
                }
            }]
        });
    }

    // *********************************************
    //  EWViewComponentManager
    // *********************************************

    EasyWeb.EWViewComponentManager = function () {
    }

    EasyWeb.EWViewComponentManager.getViewComponent = function (id) {
        id = "easyweb-" + id;
        return EasyWeb.EWViewComponentManager[id];
    };

    EasyWeb.EWViewComponentManager.setViewComponent = function (id, component) {
        id = "easyweb-" + id;
        EasyWeb.EWViewComponentManager[id] = component;
    };

    EasyWeb.EWViewComponentManager.getViewComponentId = function (id) {
        return "easyweb-" + id;
    };

    EasyWeb.EWViewComponentManager.getViewComponentContainerId = function (id) {
        return "easyweb-container-" + id;
    };

    EasyWeb.EWViewComponentManager.getViewComponentDataId = function (id) {
        return "easyweb-data-" + id;
    };

    EasyWeb.EWViewComponentManager.applyThemes = function (type, options) {
        var func;
        options = (options ? options : {});
        switch (type) {
            case "grid":
                {
                    func = EasyWeb.EWViewComponentManager._applyThemes_grid;
                    break;
                }
            default:
                throw "The type '" + type + "' is not supported.";
        }
        func(options);
    }

    EasyWeb.EWViewComponentManager._applyThemes_grid = function (options) {
        var table = (options.id ? $("#" + EasyWeb.EWViewComponentManager.getViewComponentId(options.id)) : $(".easyweb-grid table"));
        var head = $("thead", table);
        var foot = $("tfoot", table);
        var body = $("tbody", table);

        table.addClass("ui-widget ui-helper-reset");
        head.addClass("ui-helper-reset ui-state-default ui-widget-header");
        foot.addClass("ui-helper-reset ui-widget-content");
        body.addClass("ui-helper-reset ui-widget-content");
    }

    EasyWeb.EWViewComponentManager.EWGrid = function () {
    }

    EasyWeb.EWViewComponentManager.EWGrid.applySort = function (id, sortFieldName, sortDirFieldName) {
        var grid = EasyWeb.EWViewComponentManager.getViewComponent(id);
        var gridId = EasyWeb.EWViewComponentManager.getViewComponentId(id);
        var extra = grid.get_dataExtra();
        $.each($("#" + gridId + " thead tr th"), function (index, value) {
            var anchor = $("a", this);
            if (anchor.length > 0) {
                var sort = anchor.url().param(sortFieldName);
                var text = anchor.text();
                var html = $("<span></span>").text(text);
                anchor.html(html);
                if (sort == extra.sort) {
                    switch (extra.sortDir.toLowerCase()) {
                        case "ascending":
                        case "asc":
                            anchor.append("<span class='ui-icon ui-icon-triangle-1-n'></span>");
                            break;
                        case "descending":
                        case "desc":
                            anchor.append("<span class='ui-icon ui-icon-triangle-1-s'></span>");
                            break;
                    }
                }
            } else {
                var header = $(this);
                var text = header.text();
                var html = $("<span></span>").text(text);
                header.html(html);
            }
        });
    }

    // *********************************************
    //  EWViewComponent
    // *********************************************

    EasyWeb.EWViewComponent = oo.Base({
        _init: function (id, name, data) {
            if (id == null || id.length == 0) throw "The parameter id cannot be null, undefined or empty.";
            if (name == null || name.length == 0) throw "The parameter name cannot be null, undefined or empty.";

            this._componentId = id;
            this._componentName = name;
            this._data = data;
        },

        get_componentId: function () {
            return this._componentId;
        },

        get_componentName: function () {
            return this._componentName;
        },

        get_data: function () {
            return this._data;
        },

        get_viewComponent: function () {
            return $("#" + EasyWeb.EWViewComponentManager.getViewComponentId(this._componentId));
        }
    });

    // *********************************************
    //  EWGrid
    // *********************************************

    EasyWeb.EWGrid = EasyWeb.EWViewComponent({
        _init: function (id, name, data, options) {
            this._options = options ? options : {};
        },

        get_dataKey: function () {
            var data = this.get_data();
            return data ? data.key : null;
        },

        get_dataSource: function () {
            var data = this.get_data();
            return data ? data.records : [];
        },

        get_dataExtra: function () {
            var data = this.get_data();
            return data.extra ? data.extra : {};
        },

        get_selectedRecord: function () {
            var extra = this.get_dataExtra();
            return extra.select >= 0 ? this.getRecordByIndex(extra.select) : null;
        },

        get_selectedRecordIndex: function () {
            var extra = this.get_dataExtra();
            return extra.select;
        },

        getRecordByKey: function (key) {
            var dataKey = this.get_dataKey();
            var dataSource = this.get_dataSource();
            var index = dataSource.length;
            for (; --index > -1;) {
                var record = dataSource[index];
                var recordKey = eval("record." + dataKey);
                if (recordKey == key) {
                    return record;
                }
            }
        },

        getRecordByIndex: function (index) {
            var dataSource = this.get_dataSource();
            return dataSource[index];
        }
    });

    // *********************************************
    //  Admin
    // *********************************************

    EasyWeb.EWAdmin = function () {
    }

    EasyWeb.EWAdmin.refreshEWText = function (id) {
        if (id[0] != "#") {
            id = "#" + id;
        }
        var array = [];
        $.each($("tbody tr", $(id + " + table")), function () {
            var columns = $("td", this);
            array.push({ Name: $(columns[1]).text(), Text: $("textarea", columns[4]).val() });
        });
        $(id).val(JSON.stringify(array));
    }

    EasyWeb.EWAdmin.initEWConfigurationLanguageModel = function () {
        var checkbox1 = $(".easyweb-ewdefaultlanguage input[type='checkbox']").first();
        var checkbox2 = $(".easyweb-ewdefaultlanguage input[type='checkbox']").last();
        var select = $(".easyweb-ewdefaultlanguage select");

        function _refreshSelect() {
            if (checkbox2.prop("checked")) {
                select.attr("disabled", "disabled");
            } else {
                if (!checkbox1.prop("checked")) {
                    select.removeAttr("disabled");
                }
            }
        }

        function _refreshNonDefault() {
            if (checkbox1.prop("checked")) {
                select.attr("disabled", "disabled");
                checkbox2.attr("disabled", "disabled");
            } else {
                checkbox2.removeAttr("disabled");
                _refreshSelect();
            }
        }

        _refreshNonDefault();

        checkbox1.change(_refreshNonDefault);
        checkbox2.change(_refreshSelect);
    }

    // *********************************************
    //  EWBaseRouteConfiguration
    // *********************************************

    EasyWeb.EWAdmin.EWBaseRouteConfiguration = oo.Base({
        _init: function (
            uiUrl, uiHandler, uiDefaults, uiConstraints, uiNamespaces, uiValue,
            defaultUrl, constraintUrl, namespaceUrl,
            editText, deleteText,
            windowTitle, okButtonText, cancelButtonText, closeText, errorText,
            addFunc, editFunc, deleteFunc) {
            if (uiUrl) {
                this.uiUrl = $(uiUrl);
            }

            if (uiHandler) {
                this.uiHandler = $(uiHandler);
            }

            if (uiDefaults) {
                this.uiDefaults = $(uiDefaults);
            }

            if (uiConstraints) {
                this.uiConstraints = $(uiConstraints);
            }

            if (uiNamespaces) {
                this.uiNamespaces = $(uiNamespaces);
            }

            if (uiValue) {
                this.uiValue = $(uiValue);
            }

            this.defaultUrl = defaultUrl;
            this.constraintUrl = constraintUrl;
            this.namespaceUrl = namespaceUrl;

            this.editText = editText;
            this.deleteText = deleteText;

            this.windowTitle = windowTitle;
            this.okButtonText = okButtonText;
            this.cancelButtonText = cancelButtonText;
            this.closeText = closeText;
            this.errorText = errorText;

            this.addFunc = addFunc;
            this.editFunc = editFunc;
            this.deleteFunc = deleteFunc;
        },

        get_uiUrl: function () {
            return this.uiUrl;
        },

        get_uiHandler: function () {
            return this.uiHandler;
        },

        get_uiDefaults: function () {
            return this.uiDefaults;
        },

        get_uiConstraints: function () {
            return this.uiConstraints;
        },

        get_uiNamespaces: function () {
            return this.uiNamespaces;
        },

        get_uiValue: function () {
            return this.uiValue;
        },

        get_defaultUrl: function () {
            return this.defaultUrl;
        },

        get_constraintUrl: function () {
            return this.constraintUrl;
        },

        get_namespaceUrl: function () {
            return this.namespaceUrl;
        },

        get_editText: function () {
            return this.editText;
        },

        get_deleteText: function () {
            return this.deleteText;
        },

        get_windowTitle: function () {
            return this.windowTitle;
        },

        get_okButtonText: function () {
            return this.okButtonText;
        },

        get_cancelButtonText: function () {
            return this.cancelButtonText;
        },

        get_closeText: function () {
            return this.closeText;
        },

        get_errorText: function () {
            return this.errorText;
        },

        addActions: function (tr) {
            var td = $("<td class='easyweb-ewsimple-action-cell'></td>");
            td.append($("<a href='javascript:void(0)' class='easyweb-ewsimple-button easyweb-ewsimple-table-button'></a>").text(this.editText).click(this.editFunc));
            td.append($("<a href='javascript:void(0)' class='easyweb-ewsimple-button easyweb-ewsimple-table-button'></a>").text(this.deleteText).click(this.deleteFunc));
            tr.append(td);
        },

        hasUrl: function () {
            return this.uiUrl ? true : false;
        },

        hasHandler: function () {
            return this.uiHandler ? true : false;
        },

        hasDefaults: function () {
            return this.uiDefaults ? true : false;
        },

        hasConstraints: function () {
            return this.uiConstraints ? true : false;
        },

        hasNamespaces: function () {
            return this.uiNamespaces ? true : false;
        },

        hasValue: function () {
            return this.uiValue ? true : false;
        },

        initDefaults: function (value) {
            for (var i = 0; i < value.Defaults.length; i++) {
                var item = value.Defaults[i];
                var tr = $("<tr></tr>").append($("<td></td>").text(item.Name))
                                       .append($("<td></td>").text(item.Value));
                if (item.Optional) {
                    tr.append("<td><input type='checkbox' disabled='disabled' checked='checked' value='true'/></td>");
                } else {
                    tr.append("<td><input type='checkbox' disabled='disabled' value='false'/></td>");
                }
                this.addActions(tr);
                $("tbody", this.uiDefaults).append(tr);
            }
            $("tfoot a", this.uiDefaults).click(this.addFunc);
        },

        initConstraints: function (value) {
            for (var i = 0; i < value.Constraints.length; i++) {
                var item = value.Constraints[i];
                var tr = $("<tr></tr>").append($("<td></td>").text(item.Name))
                                       .append($("<td></td>").text(item.Value));
                this.addActions(tr);
                $("tbody", this.uiConstraints).append(tr);
            }
            $("tfoot a", this.uiConstraints).click(this.addFunc);
        },

        initNamespaces: function (value) {
            for (var i = 0; i < value.Namespaces.length; i++) {
                var item = value.Namespaces[i];
                var tr = $("<tr></tr>").append($("<td></td>").text(item.Name));
                this.addActions(tr);
                $("tbody", this.uiNamespaces).append(tr);
            }
            $("tfoot a", this.uiNamespaces).click(this.addFunc);
        },

        refreshUrl: function (value) {
            value.Url = this.uiUrl.val();
        },

        refreshHandler: function (value) {
            value.Handler = this.uiHandler.val();
        },

        refreshDefaults: function (value) {
            value.Defaults = [];
            $.each($("tbody tr", this.uiDefaults), function () {
                var tds = $("td", this);
                var obj = {
                    Name: $(tds[0]).text(),
                    Value: $(tds[1]).text()
                };
                if ($("input", tds[2]).val() == "true") {
                    obj.Optional = true;
                } else {
                    obj.Optional = false;
                }
                value.Defaults.push(obj);
            });
        },

        refreshConstraints: function (value) {
            value.Constraints = [];
            $.each($("tbody tr", this.uiConstraints), function () {
                var tds = $("td", this);
                var obj = {
                    Name: $(tds[0]).text(),
                    Value: $(tds[1]).text()
                };
                value.Constraints.push(obj);
            });
        },

        refreshNamespaces: function (value) {
            value.Namespaces = [];
            $.each($("tbody tr", this.uiNamespaces), function () {
                var tds = $("td", this);
                var obj = {
                    Name: $(tds[0]).text()
                };
                value.Namespaces.push(obj);
            });
        },

        initialize: function () {
            var value = $.parseJSON(this.uiValue.val());

            if (this.hasDefaults()) {
                this.initDefaults(value);
            }

            if (this.hasConstraints()) {
                this.initConstraints(value);
            }

            if (this.hasNamespaces()) {
                this.initNamespaces(value);
            }
        },

        refresh: function () {
            var value = {};

            if (this.hasUrl()) {
                this.refreshUrl(value);
            }

            if (this.hasHandler()) {
                this.refreshHandler(value);
            }

            if (this.hasDefaults()) {
                this.refreshDefaults(value);
            }

            if (this.hasConstraints()) {
                this.refreshConstraints(value);
            }

            if (this.hasNamespaces()) {
                this.refreshNamespaces(value);
            }

            this.uiValue.val(JSON.stringify(value));
        },

        addRecord: function (self, source) {
            var ths = $("thead tr th", $(source).closest("table"));
            var actionUrl;

            switch (ths.size()) {
                case 4: // defaults
                    {
                        actionUrl = self.get_defaultUrl();
                        break;
                    }
                case 3: // constraints
                    {
                        actionUrl = self.get_constraintUrl();
                        break;
                    }
                case 2: // namespaces
                    {
                        actionUrl = self.get_namespaceUrl();
                        break;
                    }
            }

            $.ajax(actionUrl, {
                cache: false,
                dataType: "html",
                type: "POST"
            }).done(function (html) {
                html = $("<div id='easyweb-container-create'></div>").append(html);
                EasyWeb.EWHelpers.modalDialog(self.get_windowTitle(), html, function () {
                    var html = $("#easyweb-container-create fieldset div");
                    switch (ths.size()) {
                        case 4: // defaults
                            {
                                var tr = $("<tr></tr>").append($("<td></td>").text($("input", $(html[0])).val()))
                                                       .append($("<td></td>").text($("input", $(html[1])).val()));
                                if ($("input[type='checkbox']", $(html[2])).prop("checked")) {
                                    tr.append("<td><input type='checkbox' disabled='disabled' checked='checked' value='true'/></td>");
                                } else {
                                    tr.append("<td><input type='checkbox' disabled='disabled' value='false'/></td>");
                                }
                                self.addActions(tr);
                                $("tbody", self.get_uiDefaults()).append(tr);
                                break;
                            }
                        case 3: // constraints
                            {
                                var tr = $("<tr></tr>").append($("<td></td>").text($("input", $(html[0])).val()))
                                                       .append($("<td></td>").text($("input", $(html[1])).val()));
                                self.addActions(tr);
                                $("tbody", self.get_uiConstraints()).append(tr);
                                break;
                            }
                        case 2: // namespaces
                            {
                                var tr = $("<tr></tr>").append($("<td></td>").text($("input", $(html[0])).val()));
                                self.addActions(tr);
                                $("tbody", self.get_uiNamespaces()).append(tr);
                                break;
                            }
                    }
                }, self.get_okButtonText(), self.get_cancelButtonText(), self.get_closeText(), 600);
            }).fail(function () {
                EasyWeb.EWHelpers.messageDialog(self.get_errorText(), self.get_windowTitle(), self.get_okButtonText(), self.get_closeText());
            });
        },

        editRecord: function (self, source) {
            var value = {};
            var actionUrl;

            var tds = $("td", $(source).closest("tr"));
            switch (tds.size()) {
                case 4: // defaults
                    {
                        value.Name = $(tds[0]).text();
                        value.Value = $(tds[1]).text();
                        value.Optional = $("input[type='checkbox']", tds[2]).attr("checked") ? true : false;
                        actionUrl = self.get_defaultUrl();
                        break;
                    }
                case 3: // constraints
                    {
                        value.Name = $(tds[0]).text();
                        value.Value = $(tds[1]).text();
                        actionUrl = self.get_constraintUrl();
                        break;
                    }
                case 2: // namespaces
                    {
                        value.Name = $(tds[0]).text();
                        actionUrl = self.get_namespaceUrl();
                        break;
                    }
            }

            $.ajax(actionUrl, {
                cache: false,
                dataType: "html",
                data: { value: JSON.stringify(value) },
                type: "POST"
            }).done(function (html) {
                html = $("<div id='easyweb-container-edit'></div>").append(html);
                EasyWeb.EWHelpers.modalDialog(self.get_windowTitle(), html, function () {
                    var html = $("#easyweb-container-edit fieldset div");
                    switch (tds.size()) {
                        case 4: // defaults
                            {
                                $(tds[0]).text($("input", $(html[0])).val());
                                $(tds[1]).text($("input", $(html[1])).val());
                                if ($("input[type='checkbox']", $(html[2])).prop("checked")) {
                                    $(tds[2]).html("<input type='checkbox' disabled='disabled' checked='checked' value='true'/>");
                                } else {
                                    $(tds[2]).html("<input type='checkbox' disabled='disabled' value='false'/>");
                                }
                                break;
                            }
                        case 3: // constraints
                            {
                                $(tds[0]).text($("input", $(html[0])).val());
                                $(tds[1]).text($("input", $(html[1])).val());
                                break;
                            }
                        case 2: // namespaces
                            {
                                $(tds[0]).text($("input", $(html[0])).val());
                                break;
                            }
                    }
                }, self.get_okButtonText(), self.get_cancelButtonText(), self.get_closeText(), 600);
            }).fail(function () {
                EasyWeb.EWHelpers.messageDialog(self.get_errorText(), self.get_windowTitle(), self.get_okButtonText(), self.get_closeText());
            });
        },

        deleteRecord: function (self, source) {
            $(source).closest("tr").remove();
        }
    });

    // *********************************************
    //  EWDefaultRouteConfiguration
    // *********************************************

    EasyWeb.EWAdmin.EWDefaultRouteConfiguration = EasyWeb.EWAdmin.EWBaseRouteConfiguration({
        _init: function (
            uiUrl, uiHandler, uiDefaults, uiConstraints, uiNamespaces, uiValue,
            defaultUrl, constraintUrl, namespaceUrl,
            editText, deleteText,
            windowTitle, okButtonText, cancelButtonText, closeText, errorText,
            addFunc, editFunc, deleteFunc) {
        }
    });

    // *********************************************
    //  EWDefaultWebApiRouteConfiguration
    // *********************************************

    EasyWeb.EWAdmin.EWDefaultWebApiRouteConfiguration = EasyWeb.EWAdmin.EWBaseRouteConfiguration({
        _init: function (
            uiUrl, uiHandler, uiDefaults, uiConstraints, uiNamespaces, uiValue,
            defaultUrl, constraintUrl, namespaceUrl,
            editText, deleteText,
            windowTitle, okButtonText, cancelButtonText, closeText, errorText,
            addFunc, editFunc, deleteFunc) {
        }
    });

    // *********************************************
    //  EWDefaultCacheConfiguration
    // *********************************************

    EasyWeb.EWAdmin.EWDefaultCacheConfiguration = oo.createClass({
        _create: function (
            url,
            formCacheType, formMemcachedServers, formAppFabricName, formAppFabricServers,
            editText, deleteText,
            windowTitle, okButtonText, cancelButtonText, closeText, errorText,
            addFunc, editFunc, deleteFunc) {
            this.url = url;

            this.formCacheType = $(formCacheType);
            this.formMemcachedServers = $(formMemcachedServers);
            this.formAppFabricName = $(formAppFabricName);
            this.formAppFabricServers = $(formAppFabricServers);

            this.editText = editText;
            this.deleteText = deleteText;

            this.windowTitle = windowTitle;
            this.okButtonText = okButtonText;
            this.cancelButtonText = cancelButtonText;
            this.closeText = closeText;
            this.errorText = errorText;

            this.addFunc = addFunc;
            this.editFunc = editFunc;
            this.deleteFunc = deleteFunc;
        },

        get_url: function () {
            return this.url;
        },

        get_editText: function () {
            return this.editText;
        },

        get_deleteText: function () {
            return this.deleteText;
        },

        get_windowTitle: function () {
            return this.windowTitle;
        },

        get_okButtonText: function () {
            return this.okButtonText;
        },

        get_cancelButtonText: function () {
            return this.cancelButtonText;
        },

        get_closeText: function () {
            return this.closeText;
        },

        get_errorText: function () {
            return this.errorText;
        },

        _buildServersHtml: function (value, table) {
            table = $(table);
            var servers = $.parseJSON(value);
            for (var i = 0; i < servers.length; i++) {
                var server = servers[i];
                var tr = $("<tr></tr>").append($("<td></td>").text(server.Address))
                                       .append($("<td></td>").text(server.Port));
                this.addActions(tr);
                $("tbody", table).append(tr);
            }
            $("tfoot a", table).click(this.addFunc);
        },

        _refreshServers: function (table, hidden) {
            table = $(table);
            hidden = $(hidden);
            var servers = [];
            $.each($("tbody tr", table), function () {
                var tds = $("td", this);
                var obj = {
                    Address: $(tds[0]).text(),
                    Port: $(tds[1]).text()
                };
                servers.push(obj);
            });
            hidden.val(JSON.stringify(servers));
        },

        addActions: function (tr) {
            var td = $("<td class='easyweb-ewsimple-action-cell'></td>");
            td.append($("<a href='javascript:void(0)' class='easyweb-ewsimple-button easyweb-ewsimple-table-button'></a>").text(this.editText).click(this.editFunc));
            td.append($("<a href='javascript:void(0)' class='easyweb-ewsimple-button easyweb-ewsimple-table-button'></a>").text(this.deleteText).click(this.deleteFunc));
            tr.append(td);
        },

        initialize: function (cacheType, cacheTypeValue) {
            $("input[name='easyweb-cache-type']").filter("[value='" + cacheType + "']").prop("checked", true);

            $("#easyweb-cache-type-appfabric-name").val(this.formAppFabricName.val());
            this._buildServersHtml(this.formAppFabricServers.val(), "#easyweb-appfabric-table");

            this._buildServersHtml(this.formMemcachedServers.val(), "#easyweb-memcached-table");

            if (cacheType == "custom") {
                $("#easyweb-cache-type-custom").val(cacheTypeValue);
            }
        },

        refresh: function () {
            if ($("#easyweb-cache-type-app-choose").prop("checked")) {
                this.formCacheType.val($("#easyweb-cache-type-app").val());
            }
            else if ($("#easyweb-cache-type-appfabric-choose").prop("checked")) {
                this.formCacheType.val($("#easyweb-cache-type-appfabric").val());
            }
            else if ($("#easyweb-cache-type-memcached-choose").prop("checked")) {
                this.formCacheType.val($("#easyweb-cache-type-memcached").val());
            }
            else if ($("#easyweb-cache-type-custom-choose").prop("checked")) {
                this.formCacheType.val($("#easyweb-cache-type-custom").val());
            }

            this.formAppFabricName.val($("#easyweb-cache-type-appfabric-name").val());
            this._refreshServers("#easyweb-appfabric-table", this.formAppFabricServers);

            this._refreshServers("#easyweb-memcached-table", this.formMemcachedServers);
        },

        addRecord: function (self, button) {
            $.ajax(self.get_url(), {
                cache: false,
                dataType: "html",
                type: "POST"
            }).done(function (html) {
                html = $("<div id='easyweb-container-create'></div>").append(html);
                EasyWeb.EWHelpers.modalDialog(self.get_windowTitle(), html, function () {
                    var html = $("#easyweb-container-create fieldset div");
                    var tr = $("<tr></tr>").append($("<td></td>").text($("input", $(html[0])).val()))
                                           .append($("<td></td>").text($("input", $(html[1])).val()));
                    self.addActions(tr);
                    $("tbody", $(button).closest("table")).append(tr);
                }, self.get_okButtonText(), self.get_cancelButtonText(), self.get_closeText(), 600);
            }).fail(function () {
                EasyWeb.EWHelpers.messageDialog(self.get_errorText(), self.get_windowTitle(), self.get_okButtonText(), self.get_closeText());
            });
        },

        editRecord: function (self, button) {
            var value = {};

            var tds = $("td", $(button).closest("tr"));
            value.Address = $(tds[0]).text();
            value.Port = parseInt($(tds[1]).text());

            $.ajax(self.get_url(), {
                cache: false,
                dataType: "html",
                data: { value: JSON.stringify(value) },
                type: "POST"
            }).done(function (html) {
                html = $("<div id='easyweb-container-edit'></div>").append(html);
                EasyWeb.EWHelpers.modalDialog(self.get_windowTitle(), html, function () {
                    var html = $("#easyweb-container-edit fieldset div");
                    $(tds[0]).text($("input", $(html[0])).val());
                    $(tds[1]).text($("input", $(html[1])).val());
                }, self.get_okButtonText(), self.get_cancelButtonText(), self.get_closeText(), 600);
            }).fail(function () {
                EasyWeb.EWHelpers.messageDialog(self.get_errorText(), self.get_windowTitle(), self.get_okButtonText(), self.get_closeText());
            });
        },

        deleteRecord: function (self, button) {
            $(button).closest("tr").remove();
        }
    });

    // *********************************************
    //  Temp
    // *********************************************

    EasyWeb.EWTemp = function () {
    }

    // *********************************************
    //  Init
    // *********************************************

    $(function () {
        EasyWeb.EWMaster.init();
    });

}(jQuery));
